package com.zmn.oms.third.taobao.msghandler.impl;

import com.zmn.biz.complain.common.dio.tmall.TrackComplainTmallDIO;
import com.zmn.biz.complain.dubbo.interfaces.tmall.ComplainTmallModifyRemoteService;
import org.apache.dubbo.config.annotation.Reference;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageStatus;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.taobao.TaobaoMapper;
import com.zmn.oms.third.taobao.TaobaoTmcConstants;
import com.zmn.oms.third.taobao.TaobaoTmcUtil;
import com.zmn.oms.third.taobao.dto.TmcComplaintDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 类描述：投诉消息处理器
 *
 * @author LiangHailong
 * @date 2019/07/24 17:57
 */
@Component("complaintTmcMsgHandler")
public class ComplaintTmcMsgHandler extends TmcMsgHandlerBase {
    private static final Logger logger = LoggerFactory.getLogger(ComplaintTmcMsgHandler.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Reference(version = com.zmn.biz.complain.common.constant.DubboConsts.INTERFACE_VERSION,check = false)
    private ComplainTmallModifyRemoteService complainTmallModifyRemoteService;

    /**
     * 处理投诉消息
     * @param message
     * @param status
     */
    @Override
    public void procMsg(Message message, MessageStatus status) {
        try {
            TmcComplaintDTO tmcComplaintDTO = TaobaoTmcUtil.parseMessageContent(message.getContent(), TmcComplaintDTO.class);
            saveComplaint(tmcComplaintDTO, message);
        } catch (Exception e) {
            logger.info("【{}-消息-投诉】消息处理失败，触发消息重发！ErrorMsg:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    e.getMessage());
            logger.error(e.getMessage(), e);
            status.fail(); // 消息处理失败回滚，服务端需要重发
        }
    }

    /**
     * 保存投诉
     * @param tmcComplaintDTO
     * @param message
     * @throws Exception
     */
    private void saveComplaint(TmcComplaintDTO tmcComplaintDTO, Message message) {
        TrackComplainTmallDIO complainDIO = buildComplaintDIO(tmcComplaintDTO);
        if (complainDIO != null) {
            ResponseDTO<Integer> integerResponseDTO = complainTmallModifyRemoteService.addTrackComplainTmall(complainDIO);
            if (!integerResponseDTO.isSuccess()) {
                logger.info("【{}-消息-投诉】保存投诉信息错误 Message:[{}]", TaobaoTmcConstants.NAME_TMALL,
                        integerResponseDTO.getMessage());
            }
        }
    }

    /**
     * 将淘宝消息转换成投诉对象
     * @param tmcComplaintDTO
     * @return
     */
    private TrackComplainTmallDIO buildComplaintDIO(TmcComplaintDTO tmcComplaintDTO) {
        // 投诉消息中的workcark_id字段对应了工单消息中的id字段，也就是我们系统工单表中存的outerId
        String outerId = Long.toString(tmcComplaintDTO.getWorkcardId());

        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);
        List<ZsOrderWorkVO> zsOrderWorkVOS = zsOrderWorkQueryBService.listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(zsOrderWorkVOS)) {
            logger.info("【{}-消息-投诉】没找到投诉对应的工单（已忽略） OuterId:[{}]", TaobaoTmcConstants.NAME_TMALL, outerId);
            return null;
        }
        ZsOrderWorkVO orderWorkVO = zsOrderWorkVOS.get(0);
        Order order = orderService.findOrderByKey(orderWorkVO.getOrderId());
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderWorkVO.getOrderId(), orderWorkVO.getWorkId());

        TrackComplainTmallDIO complainDIO = new TrackComplainTmallDIO();

        complainDIO.setComplainTmallId(tmcComplaintDTO.getId());
        complainDIO.setOrderId(orderWork.getOrderId());
        complainDIO.setWorkId(orderWork.getWorkId());
        complainDIO.setComplainTime(tmcComplaintDTO.getSubmitTime());
        complainDIO.setCityId(order.getCityId());
        complainDIO.setCityName(orderWorkVO.getCityName());
        complainDIO.setUsername(StringUtils.defaultIfBlank(orderWorkVO.getUsername(), "用户"));
        complainDIO.setUserMobile(orderWorkVO.getUserPhone());
        complainDIO.setServProviderId(order.getCompanyId());
        complainDIO.setOperator("系统");
        complainDIO.setOperatorId(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        complainDIO.setStatus(10);  // 10:已录入 20：已处理 30：已完成 40：已取消

        String questionType = tmcComplaintDTO.getQuestionType();
        complainDIO.setContentId(Integer.parseInt(questionType));

        TaobaoMapper.RecourseQuestion recourseQuestion = TaobaoMapper.RECOURSE_QUESTION_MAP.get(questionType);
        if (recourseQuestion != null) {
            complainDIO.setContent(recourseQuestion.getText());
        }
        else {
            logger.info("【{}-消息-投诉】没找到对应的投诉问题 QuestionType:[{}]", TaobaoTmcConstants.NAME_TMALL, questionType);
        }

        return complainDIO;
    }
}
